package br.com.devteam.base.converter;

import java.text.ParseException;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.swing.text.MaskFormatter;

import br.com.devteam.base.validator.CEPValidator;

@FacesConverter(value = "CEPConverter")
public class CEPConverter implements Converter {

	@Override
	public Object getAsObject(FacesContext arg0, UIComponent arg1, String arg2) {
		
		if (arg2 != null && CEPValidator.validar(arg2)) {
			return arg2.replace("-", "");
		}
		
		return arg2;
	}

	@Override
	public String getAsString(FacesContext arg0, UIComponent arg1, Object arg2) {
		
		if (arg2 != null && arg2.toString().length() > 0) {
			try {
				MaskFormatter formatter = new MaskFormatter("#####-###");
				formatter.setValueContainsLiteralCharacters(false);
				return formatter.valueToString(arg2);
			} catch (ParseException e) {
				e.printStackTrace();	
			}
		}
		
		return null;
	}

}
